<?php

namespace app\ruinuo\controller\design;

use think\facade\Request;
use app\common\model\RuinuoTable;
use app\common\model\AdminPowerTable;
use app\common\model\RuinuoMode;
use app\common\model\RuinuoApp;
use app\common\model\RuinuoDatabase;
use app\common\model\AdminMenu;
use app\common\middleware\Auth;

class Lists
{
    protected $middleware = [Auth::class => []];

    public function Index()
    {
        if (Request::isAjax() || Request::isPost()) {
            $modeid = input('modeid');
            if (empty($modeid)) {
                return BackCode([], '203', '请传入参数');
            }
            $RuinuoTable = new RuinuoTable();
            $RuinuoApp = new RuinuoApp();
            $RuinuoMode = new RuinuoMode();
            $AdminMenu = new AdminMenu();
            $AdminPowerTable = new AdminPowerTable();
            $Mode = $RuinuoMode->where("id='" . $modeid . "' and is_delete=0")->field("name,app_id,num")->findOrEmpty()->toArray();
            if (empty($Mode)) {
                return BackCode([], '203', '请传入参数');
            }
            $App = $RuinuoApp->where("id='" . $Mode['app_id'] . "' and is_delete=0")->field("num")->findOrEmpty()->toArray();
            if (empty($App)) {
                return BackCode([], '203', '请传入参数');
            }
            $node = "" . $App['num'] . ":" . $Mode['num'] . ":index";
            $menu = $AdminMenu->where("power_node='" . $node . "' and type=2 and is_delete=0")->field("id")->findOrEmpty()->toArray();
            $table_button = [];
            $MenuButton = [];
            if ($menu) {
                $MenuButton = $AdminMenu->where("parent_id='" . $menu['id'] . "' and is_delete=0")->field("btn_class,title,position,href,power_node,where,open_type,status,id")->order('sort asc,create_time desc')->select()->toArray();
                foreach ($MenuButton as $k => $v) {
                    $v['is_sync'] = 1;
                    $table_button[] = $v;
                }
            }
            $SystemButton = $this->SystemButton($App['num'], $Mode['num']);
            foreach ($SystemButton as $k => $v) {
                $show = 1;
                foreach ($MenuButton as $kk => $vv) {
                    if ($vv['power_node'] == $v['power_node']) {
                        $show = 2;
                    }
                }
                if ($show == 1) {
                    $table_button[] = $v;
                }
            }
            $find = $RuinuoTable->where("mode_id='" . $modeid . "'")->findOrEmpty()->toArray();
            $table_cols = !empty($find['table_cols']) ? json_decode($find['table_cols'], true) : [];
            $table_tab = !empty($find['table_tab']) ? json_decode($find['table_tab'], true) : [];
            $table_power = $AdminPowerTable->where("mode_id='" . $modeid . "' and is_delete=0")->findOrEmpty()->toArray();
            $table_power['power_field'] = !empty($table_power['power_field']) ? json_decode($table_power['power_field'], true) : [];
            $table_field = $this->GetDataField($modeid, $table_cols);
            $data = [
                'mode_id' => $modeid,
                'title' => $Mode['name'],
                'source' => $this->GetSource($table_field),
                'detail' => [
                    'app_num' => $App['num'],
                    'mode_num' => $Mode['num'],
                    'menu_id' => !empty($menu['id']) ? $menu['id'] : '',
                    'is_left' => !empty($find['is_left']) ? $find['is_left'] : 2,
                    'left_title' => !empty($find['left_title']) ? $find['left_title'] : '',
                    'left_type' => !empty($find['left_type']) ? $find['left_type'] : 1,
                    'left_options' => !empty($find['left_options']) ? $find['left_options'] : '',
                    'left_mode' => !empty($find['left_mode']) ? $find['left_mode'] : '',
                    'left_key_field' => !empty($find['left_key_field']) ? $find['left_key_field'] : '',
                    'left_show_field' => !empty($find['left_show_field']) ? $find['left_show_field'] : '',
                    'left_field' => !empty($find['left_field']) ? $find['left_field'] : '',
                    'style' => !empty($find['style']) ? $find['style'] : 1,
                    'style_tpl' => !empty($find['style_tpl']) ? $find['style_tpl'] : '',
                    'tree_field' => !empty($find['tree_field']) ? $find['tree_field'] : 'parent_id',
                    'tree_name' => !empty($find['tree_name']) ? $find['tree_name'] : 'title',
                    'set_where' => !empty($find['set_where']) ? $find['set_where'] : '',
                    'asc_desc' => !empty($find['asc_desc']) ? $find['asc_desc'] : 'a.create_time desc',
                    'page_num' => !empty($find['page_num']) ? $find['page_num'] : 30,
                    'table_cols' => $table_cols,
                    'table_field' => $table_field,
                    'table_button' => $table_button,
                    'power_user' => !empty($table_power['power_user']) ? $table_power['power_user'] : '',
                    'power_role' => !empty($table_power['power_role']) ? $table_power['power_role'] : '',
                    'power_department' => !empty($table_power['power_department']) ? $table_power['power_department'] : '',
                    'table_power' => $table_power,
                    'table_tab' => $table_tab,
                ],
            ];
            return BackCode($data);
        }
        return ViewTpl('ruinuo/design/lists');
    }

    public function SystemButton($app_num, $mode_num)
    {
        $href = '/' . $app_num . '/' . $mode_num . '/';
        $node = $app_num . ':' . $mode_num . ':';
        $data = [
            ['title' => '新增', 'icon' => 'icon-add-bold', 'btn_class' => 'btn_theme_1', 'position' => 1, 'href' => $href . 'add/', 'power_node' => $node . 'add', 'open_type' => 'window', 'is_sync' => 2, 'status' => 2],
            ['title' => '修改', 'icon' => 'icon-edit', 'btn_class' => 'btn_theme_1', 'position' => 2, 'href' => $href . 'edit/?id={d.id}', 'power_node' => $node . 'edit', 'open_type' => 'window', 'is_sync' => 2, 'status' => 2],
            ['title' => '删除', 'icon' => 'icon-ashbin', 'btn_class' => 'btn_theme_2', 'position' => 2, 'href' => $href . 'delete/?id={d.id}', 'power_node' => $node . 'delete', 'open_type' => 'ajax', 'is_sync' => 2, 'status' => 2],
            ['title' => '批量删除', 'icon' => 'icon-ashbin', 'btn_class' => 'btn_theme_2', 'position' => 1, 'href' => $href . 'batch_delete/?ids={d.id}', 'power_node' => $node . 'batch_delete', 'open_type' => 'ajax', 'is_sync' => 2, 'status' => 2],
            ['title' => '查看', 'icon' => 'icon-browse', 'btn_class' => 'btn_theme_0', 'position' => 2, 'href' => $href . 'detail/?id={d.id}', 'power_node' => $node . 'detail', 'open_type' => 'window', 'is_sync' => 2, 'status' => 2],
            ['title' => '导入', 'icon' => 'icon-yunshangchuan_o', 'btn_class' => 'btn_theme_0', 'position' => 1, 'href' => $href . 'import_excel/', 'power_node' => $node . 'import_excel', 'open_type' => 'open', 'is_sync' => 2, 'status' => 2],
            ['title' => '导出', 'icon' => 'icon-share1', 'btn_class' => 'btn_theme_0', 'position' => 1, 'href' => $href . 'export_excel/', 'power_node' => $node . 'export_excel', 'open_type' => 'open', 'is_sync' => 2, 'status' => 2],
        ];
        return $data;
    }


    public function GetDataField($modeid, $value)
    {
        $RuinuoMode = new RuinuoMode();
        $Mode = $RuinuoMode->where("id=" . $modeid)->field("database,sub_database")->findOrEmpty()->toArray();
        $table = [$this->GetDataBase($Mode['database'], $value)];
        $sub_database = !empty($Mode['sub_database']) ? json_decode($Mode['sub_database'], true) : [];
        foreach ($sub_database as $k => $v) {
            $table[] = $this->GetDataBase($v['database'], $value, $v['alias']);
        }
        return $table;
    }

    public function GetDataBase($name, $value = [], $modeNum = '')
    {
        $RuinuoDatabase = new RuinuoDatabase();
        $table = $RuinuoDatabase->where("name='" . $name . "'")->field('name,comment,field')->findOrEmpty()->toArray();
        $field = !empty($table['field']) ? json_decode($table['field'], true) : [];
        $children = [];
        foreach ($field as $k => $v) {
            $ValField = $v['field'];
            if ($modeNum) {
                $ValField = $modeNum . "__" . $v['field'];
            }
            $on = false;
            foreach ($value as $kk => $vv) {
                if ($vv['field'] == $ValField) {
                    $on = true;
                }
            }
            $children[] = ['value' => $ValField, 'label' => $v['title'], 'on' => $on];
        }
        $data = [
            'value' => $table['name'],
            'label' => $table['comment'],
            'children' => $children,
        ];
        return $data;
    }

    public function GetSource($table_field = [])
    {
        $source = [
            'position' => [
                'rows' => [
                    ['label' => '左', 'value' => 'left'],
                    ['label' => '中', 'value' => 'center'],
                    ['label' => '右', 'value' => 'right']
                ],
            ],

            'edit' => [
                'rows' => [
                    ['label' => '文本框', 'value' => 'input'],
                    ['label' => '下拉框', 'value' => 'select'],
                    ['label' => '年月日', 'value' => 'date'],
                    ['label' => '年月日时分秒', 'value' => 'time'],
                    ['label' => 'switch', 'value' => 'switch'],
                ],
            ],
            'search' => [
                'rows' => [
                    ['label' => '时间搜索', 'value' => 'datetime'],
                    ['label' => '模糊搜索', 'value' => 'like'],
                    ['label' => '下拉筛选', 'value' => 'select'],
                    ['label' => 'url传参', 'value' => 'url'],
                ],
            ],
            'table_field' => [
                'rows' => $table_field,
            ],
            'select' => GetOptions('options_list'),
            'user_list' => GetOptions('admin_user_list'),
            'role_list' => GetOptions('admin_role'),
            'department_list' => GetOptions('department_list'),
            'yesno' => GetOptions('yesno'),
            'mode_list' => GetOptions('mode_list'),
            'left_type' => GetOptions('left_type'),
            'lists_style' => GetOptions('lists_style'),
            'button_type' => GetOptions('button_type'),
            'button_position' => GetOptions('button_position'),
            'page_num' => [
                'rows' => [
                    ['label' => '不分页', 'value' => '999'],
                    ['label' => '10', 'value' => '10'],
                    ['label' => '30', 'value' => '30'],
                    ['label' => '50', 'value' => '50'],
                    ['label' => '100', 'value' => '100'],
                    ['label' => '200', 'value' => '200'],
                    ['label' => '300', 'value' => '300'],
                    ['label' => '500', 'value' => '500'],
                ],
            ],
        ];
        return $source;
    }


    public function ColsAdd()
    {
        $checked = input('checked');
        $id = input('id');
        $title = input('title');
        $num = input('num');
        $RuinuoTable = new RuinuoTable();
        $find = $RuinuoTable->where("mode_id='" . $id . "'")->field("mode_id,table_cols")->find();
        if (empty($find)) {
            return BackCode([], 203, '沒有此列表');
        }
        $item = !empty($find['table_cols']) ? json_decode($find['table_cols'], true) : [];
        if ($checked == 1) {
            $ids = time() . '_' . $id . '_' . count($item);
            $item[] = ['field' => $num, 'title' => $title, 'id' => $ids];
        } else {
            foreach ($item as $k => $v) {
                if ($v['field'] == $num) {
                    unset($item[$k]);
                }
            }
        }
        $item = array_values($item);
        $updata['table_cols'] = !empty($item) ? json_encode($item, JSON_UNESCAPED_UNICODE) : '[]';
        $RuinuoTable->where("mode_id='" . $id . "'")->update($updata);
        return BackCode($item);
    }

    public function editcols()
    {
        $item = !empty(input('item')) ? json_decode(input('item'), true) : [];
        foreach ($item as $k => $v) {
            unset($item[$k]['LAY_NUM']);
            unset($item[$k]['LAY_INDEX']);
        }
        $item = array_values($item);
        $id = input('id');
        $type = input('type');
        $updata['table_cols'] = !empty($item) ? json_encode($item, JSON_UNESCAPED_UNICODE) : '[]';
        $RuinuoTable = new RuinuoTable();
        $RuinuoTable->where("mode_id='" . $id . "'")->update($updata);
        return BackCode();
    }


    public function Edit()
    {
        if (Request::isAjax() || Request::isPost()) {
            $mode_id = input('mode_id');
            if (empty($mode_id)) {
                return BackCode([], 203, '参数mode_id不能为空');
            }
            $RuinuoTable = new RuinuoTable();
            $AdminPowerTable = new AdminPowerTable();
            $sendData = input();
            $table_tab = !empty($sendData['table_tab']) ? json_decode($sendData['table_tab'], true) : [];
            $table_power = !empty($sendData['table_power']) ? json_decode($sendData['table_power'], true) : [];
            foreach ($table_tab as $k => $v) {
                unset($table_tab[$k]['LAY_NUM']);
                unset($table_tab[$k]['LAY_INDEX']);
            }
            foreach ($table_power as $k => $v) {
                unset($table_power[$k]['LAY_NUM']);
                unset($table_power[$k]['LAY_INDEX']);
            }
            $tableData = [
                'name' => input('mode_name') ?: '',
                'mode_id' => $mode_id,
                'style' => input('style') ?: 1,
                'style_tpl' => input('style_tpl') ?: NULL,
                'tree_field' => input('tree_field') ?: 'parent_id',
                'tree_name' => input('tree_name') ?: 'title',
                'set_where' => input('set_where') ?: '1=1',
                'asc_desc' => input('asc_desc') ?: 'a.create_time desc',
                'page_num' => input('page_num') ?: '30',
                'is_left' => input('is_left') ?: '2',
                'left_title' => input('left_title') ?: NULL,
                'left_type' => input('left_type') ?: 1,
                'left_mode' => input('left_mode') ?: NULL,
                'left_options' => input('left_options') ?: NULL,
                'left_key_field' => input('left_key_field') ?: NULL,
                'left_show_field' => input('left_show_field') ?: NULL,
                'left_field' => input('left_field') ?: NULL,
                'table_tab' => json_encode($table_tab, JSON_UNESCAPED_UNICODE)
            ];
            $Lists = $RuinuoTable->where("mode_id='" . $mode_id . "' and is_delete=0")->count();
            if ($Lists) {
                $tableData['update_id'] = GetToken('id');
                $tableData['update_time'] = date('Y-m-d H:i:s');
                $RuinuoTable->where("mode_id='" . $mode_id . "'")->update($tableData);
            } else {
                $tableData['create_id'] = GetToken('id');
                $tableData['create_time'] = date('Y-m-d H:i:s');
                $tableData['id'] = GetSnowID();
                $RuinuoTable->insert($tableData);
            }
            $power_node = input('app_num') . ':' . input('mode_num');
            if (empty(input('power_user')) && empty(input('power_role')) && empty(input('power_department')) && empty($table_power))
            {
                return BackCode();
            }
            $powerData = [
                'mode_id' => $mode_id,
                'name' => input('mode_name') ?: NULL,
                'power_user' => input('power_user') ?: NULL,
                'power_role' => input('power_role') ?: NULL,
                'power_department' => input('power_department') ?: NULL,
                'power_node' => $power_node,
                'power_field' => json_encode($table_power, JSON_UNESCAPED_UNICODE),
                'update_id' => GetToken('id'),
                'update_time' => date('Y-m-d H:i:s')
            ];
            $Lists = $AdminPowerTable->where("mode_id='" . $mode_id . "' and is_delete=0")->count();
            if ($Lists) {
                unset($powerData['power_node']);
                $AdminPowerTable->where("mode_id='" . $mode_id . "'")->update($powerData);
            } else {
                $powerData['create_id'] = GetToken('id');
                $powerData['create_time'] = date('Y-m-d H:i:s');
                $powerData['id'] = GetSnowID();
                $AdminPowerTable->insert($powerData);
            }
            return BackCode();
        }
    }
}
